package com.zhx.sweet.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zhanghaixuan
 * @create 2018/4/18-上午11:17
 **/
public class DefaultCuestomAuthentionFailedHandler implements CuestomAuthentionFailedHandler {
    private  final static Logger logger = LoggerFactory.getLogger(MyAuthentionFailedHandler.class);

    //spring 启动的时候自动注册的一个mapper 可以转换类
    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType("application/json,charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        PrintWriter out = httpServletResponse.getWriter();

        logger.info("登录失败!");

        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        httpServletResponse.setContentType("application/json,charset=UTF-8");
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(ResponseEntity.status(500).body(e.getMessage())));
    }
}
